﻿using System.Threading;
using ESoft.Redis;

namespace ESoft.Locking
{
    /// <summary>
    /// 分布式锁
    /// </summary>
    public class RedisDistributeLock : IDistributeLock
    {
        private readonly IRedisService _redisService;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="redisService"></param>
        public RedisDistributeLock(IRedisService redisService)
        {
            _redisService = redisService;
        }

        /// <summary>
        /// 获取锁
        /// </summary>
        /// <param name="lockKey"></param>
        /// <param name="timeoutSpan"></param>
        /// <returns></returns>
        public bool AcquireLock(string lockKey, double timeoutSpan = 10000)
        {
            var spinWait = new SpinWait();
            while (!_redisService.SetNx(lockKey, 1, timeoutSpan))
            {
                spinWait.SpinOnce();
            }

            return true;
        }

        /// <summary>
        /// 释放锁
        /// </summary>
        /// <param name="lockKey"></param>
        /// <returns></returns>
        public bool ReleaseLock(string lockKey)
        {
            return _redisService.Remove(lockKey);
        }
    }
}
